package session;

import cart.ShoppingCart;
import entity.Product;
import javax.ejb.EJB;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author osman
 */
@ManagedBean(name = "cartManager")
@SessionScoped
public class CartManager {

	@PersistenceContext(unitName = "jsf_crudPU")
	private EntityManager em;
	private ShoppingCart cart;
	@EJB
	private ProductFacade productFacade;

	public String addProduct() {
		HttpServletRequest request =
						(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

		String productId = request.getParameter("productId");
		String categoryId = request.getParameter("categoryId");

		if (productId != null) {
			// if user is adding item to cart for first time
			// create cart object and attach it to user session
			if (cart == null) {
				cart = new ShoppingCart();
				HttpSession session = request.getSession();
				session.setAttribute("cart", cart);
			}

			Product product = productFacade.find(Integer.parseInt(productId));
			cart.addItem(product);
		}
		return "category.xhtml?cid=1";
	}

	public String updateProduct() {
		HttpServletRequest request =
						(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

		String productId = request.getParameter("productId");

		if (productId != null) {
			String quantity = request.getParameter("quantity");

			Product product = productFacade.find(Integer.parseInt(productId));
			cart.update(product, quantity);
		}
		return "cart.xhtml";
	}

	public ShoppingCart getCart() {
		return cart;
	}
}
